<style>
	.ui-datepicker {
		width: 175px;
	}
	
	#events_calendar * {
		color: #666 !important;
	}
	
	#events_calendar .hasEvents a {
		font-weight: bold;
		color: black;
	}
	
	#edit_event {
		padding-left:170px;  
		text-align:left;
	}
	
	#edit_event button {
		margin-top:10px;
		margin-left:180px;
	}
</style>

<div id='events_calendar'></div>

<div class="block" id='events'>
	<div class="heading">
		<h2>CОБЫТИЯ</h2>
		<a href="#" class="add-link">Add</a>
	</div>
	<div></div>
</div>

{literal}
<script id='event_tpl' type="text/x-jsmart-tmpl">
	<div id='edit_event'>
		<form>
		<input type=hidden name='id'    value='{$id}'>
		<input type=hidden name='day'   value='{$day}'>
		<input type=hidden name='month' value='{$month}'>
		<input type=hidden name='year'  value='{$year}'>
		<strong style='font-size:16px'>{$day|prepend0}.{$month|prepend0}.{$year}</strong>
		<br>
		<textarea name='title' cols=50 rows=4>{$title}</textarea>
		<br>
		<input type=hidden name='txt' value=''>
		</form>
		<button type=button id='event_save'>Сохранить</button>
	</div>
</script>

<script id='event_list_tpl' type="text/x-jsmart-tmpl">
	<em class="date">{$day|prepend0}.{$month|prepend0}.{$year}</em>
	<ul class="event-list">
	{foreach $events as $event}
		<li event_id={$event[0]}>
			{if $event[7]}
				<span><a href='#' event_id='{$event[0]}'>{$event[2]}</a></span> <a href="#" class="remove-link">Remove</a>
			{else}
				<span>{$event[2]}</span>
			{/if}
		</li>
	{/foreach}
	</ul>
</script>

<script>
	function editEvent(event) {
		popup('Событие', $('#event_tpl').html().fetch(event))
			.find('#event_save').click(function(e) {
				var event = $.extend($('#popupBox form').serializeObject(),{ 'clientId':clientId });
				if (!parseInt(event.id)) {
					delete event.id;
					call('admin.doAction',{ 'id':'event_add','params':event }).done(function() {
						showEventList(event.year,event.month,event.day);
						getMonthEvents(event.year,event.month);
					});
				} else { 
					var params = {
						'id': event.id,
						'title': event.title,
						'txt': '',
						'year': event.year,
						'month': event.month,
						'day': event.day
					};
					call('admin.doAction',{ 'id':'event_edit','params':params }).done(function() {
						showEventList(event.year,event.month,event.day);
						getMonthEvents(event.year,event.month);
					});
				}
				hidePopup();
			});
		
	}
	
	function showEventList(year,month,day) {
		var list = $('#events div:nth-child(2)');
		list.empty();
		call('admin.getList',{ 'id':'events','params':{ 'clientId':clientId }, 'filter':{ 'year':year, 'month':month, 'day':day } }).done(function(events) {
			list.html( $('#event_list_tpl').html().fetch({ 'year':year, 'month':month, 'day':day, 'events':events }) );
			list.find('.remove-link').click(function(e){
				e.preventDefault();
				call('admin.doAction', { 'id':'event_del', 'params':{ 'id':$(e.target).closest('li').attr('event_id') } }).done(function(){
					showEventList(year,month,day);
					getMonthEvents(year,month);
				});
			});
			list.find('.event-list li span a:first-child').click(function(e){
				e.preventDefault();
				editEvent({ 'id':$(this).attr('event_id'), 'title':$(this).html(), 'day':day, 'month':month, 'year':year });
			});
		});
	}
	
	function getMonthEvents(year, month) {
		$.ajax('/cf/call/admin.getList',{
			async:false,
			data: { 'id':'events', 'params':{ 'clientId':clientId }, 'filter':{ 'year':year, 'month':month } }, 
			success: function(monthEvents) {
				if (!(year in events)) {
					events[year] = { };
				}
				events[year][month] = { };
				for (var i=0; i<monthEvents.length; ++i) {
					if (monthEvents[i][6] in events[year][month]) {
						events[year][month][monthEvents[i][6]] += '\n' + monthEvents[i][2];
					} else {
						events[year][month][monthEvents[i][6]] = monthEvents[i][2];
					}
				}
			} 
		});
	}
	
	var events = {};   //year -> month -> date - titles of events
	
	$( function() {
		$('#events_calendar').datepicker({
			beforeShowDay: function(dt) { 
				var year = dt.getFullYear();
				var month = dt.getMonth()+1;
				var day = dt.getDate();
				if (!(year in events) || !(month in events[year])) {
					getMonthEvents(year,month);
				}
				return [
					true,                                                         //is selectable
					(day in events[year][month]) ? 'hasEvents' : '',              //CSS class names
					(day in events[year][month]) ? events[year][month][day] : ''  //popup tooltip
				];
			},
			onSelect: function(dateText, inst) {
				var dt = dateText.match(/0?(\d{1,2})\.0?(\d{1,2})\.(\d{4})/);
				showEventList(dt[3],parseInt(dt[2]),parseInt(dt[1]));
			}
		});
		
		$('#events .add-link').click(function(e){
			var dt = $('#events_calendar').datepicker("getDate");
			if (!dt) {
				return;
			}
			editEvent({ 'id':0, 'title':'', 'day':dt.getDate(), 'month':dt.getMonth()+1, 'year':dt.getFullYear() });
		});
		
		showEventList((new Date).getFullYear(), (new Date).getMonth()+1, (new Date).getDate());
	} );
</script>
{/literal}